package AneRouge;


import java.util.ArrayList;
import java.util.HashSet;
import javax.swing.JFrame;




class Test {

	AneRougeBoard board;

	AneRougePanel panel;

	enum Status {
		WIN, EXAUSTED, FAIL
	};

	long delay = 10;

	int MAX_DEPTH = 400;

	HashSet visited = new HashSet();

	boolean display = true;

	public static void main(String args[]) {
		Test test = new Test();
		test.search(0);
	}

	Test() {
		board = new AneRougeBoard();
		if (display) {
			JFrame frame = new JFrame();
			panel = new AneRougePanel(board);
			frame.setContentPane(panel);
			panel.addMouseListener(panel);
			panel.addMouseMotionListener(panel);
			frame.pack();
			frame.setVisible(true);
		}
	}

	public Status search(int deep) {
		deep++;
		// Node root = new Node(null, null,board.hashCode());

		AneRougeMove moves[] = getMoves();

		AneRougeMove move = null;

		boolean dirty = false;

		for (int i = 0; i < moves.length; i++) {
			move = moves[i];
			// System.out.println("MOVING: " + deep + " " + move.block + " " +
			// move.dir);
			board.moveBloc(move.block, move.dir);
			if (board.hasWon()) {
				System.out.print(" Phewww !!!!! ");
				repaint();
				return Status.WIN;
			} else {
				Long boardKey = board.longHashCode();
				if (visited.contains(boardKey)) {
					// System.out.println(" Already seen this one ");
				} else {
					visited.add(boardKey);
					System.out.println(deep + "   " + visited.size());
					repaint();
					dirty = true;
					if (search(deep) == Status.WIN)
						return Status.WIN;
				}
			}
			board.unMoveBloc(move.block, move.dir);
			if (dirty)
				repaint();
			dirty = false;

		}
		// System.out.println(" Exausted at " + deep);
		return Status.FAIL;
	}

	void repaint() {
		if (panel == null)
			return;
		panel.repaint();
		try {
			Thread.sleep(delay);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	ArrayList<AneRougeMove> moves = new ArrayList<AneRougeMove>();

	AneRougeMove[] getMoves() {
		moves.clear();
		for (int i = 0; i < AneRougeBoard.numBloc; i++) {
			for (int j = 0; j < 4; j++) {
			//	try {
					if (board.canMove(i, j))
						moves.add(new AneRougeMove(i, j));
		//		} catch (Throwable e) {
		//			e.printStackTrace();
		//		}
			}

		}
		AneRougeMove[] ret = new AneRougeMove[moves.size()];
		ret = moves.toArray(ret);

		return ret;
	}
}
